package leetcode.editor.cn.dsa26_unionfind;
//给你一个由 '1'（陆地）和 '0'（水）组成的的二维网格，请你计算网格中岛屿的数量。
// 岛屿总是被水包围，并且每座岛屿只能由水平方向和/或竖直方向上相邻的陆地连接形成。
// 此外，你可以假设该网格的四条边均被水包围。
//
// 示例 1：
//输入：grid = [
//  ["1","1","1","1","0"],
//  ["1","1","0","1","0"],
//  ["1","1","0","0","0"],
//  ["0","0","0","0","0"]
//]
//输出：1
//
// 示例 2： 
//输入：grid = [
//  ["1","1","0","0","0"],
//  ["1","1","0","0","0"],
//  ["0","0","1","0","0"],
//  ["0","0","0","1","1"]
//]
//输出：3
//
// 提示： 
// m == grid.length
// n == grid[i].length 
// 1 <= m, n <= 300 
// grid[i][j] 的值为 '0' 或 '1' 
// 
// Related Topics 深度优先搜索 广度优先搜索 并查集 
// 👍 928 👎 0

public class NumberOfIslands200_2 {
    public static void main(String[] args) {
        Solution solution = new NumberOfIslands200_2().new Solution();
        char[][] grid = {
                {'1','1','1','1','0'},
                {'1','1','0','1','0'},
                {'1','1','0','0','0'},
                {'0','0','0','0','0'}};
        System.out.println(solution.numIslands(grid));
    }

    //leetcode submit region begin(Prohibit modification and deletion)
    class Solution {
        /**
         * 并查集
         */
        public class UnionFindSet {
            private int[] parent;
            private int count;
            public int getCount() {
                return count;
            }
            public UnionFindSet(int len) {
                count = len;
                parent = new int[len];
                // 简单点，直接让每个节点的父节点都指向自身
                for (int i = 0; i < len; i++) {
                    parent[i] = i;
                }
            }
            public int find(int i) {
                // 不做路径压缩，因为节点层次不会很长
                while (parent[i] != i) {
                    i = parent[i];
                }
                return i;
            }
            public void union(int x, int y) {
                int rootX = find(x);
                int rootY = find(y);
                if (rootX != rootY) {
                    // 一般来讲x节点多的概率更高一些
                    parent[rootY] = rootX;
                    count--;
                }
            }
        }
        public int numIslands(char[][] grid) {
            int m = grid.length;
            int n = grid[0].length;
            // 记录“水”的个数
            int illegalCount = 0;
            UnionFindSet uf = new UnionFindSet(m * n);
            // 1.遍历二维网格，查找每个陆地(1)节点
            // 因为有了union的判断，所以不需要进行标记
            for (int i = 0; i < m; i++) {
                for (int j = 0; j < n; j++) {
                    if (grid[i][j] == '1') {
                        // 2.使用并查集对象合并四个方向上的邻接点
                        // 优化：由于我们是从上往下、从左往右遍历每一个节点
                        // 因此对于每个节点来说只需要遍历右和下方向即可，边界判断同理
                        int index = i * n + j;
                        if (j + 1 < n && grid[i][j + 1] == '1') {
                            // uf.union(i * n + j, i * n + j + 1);
                            uf.union(index, index + 1);
                        }
                        if (i + 1 < m && grid[i + 1][j] == '1') {
                            // uf.union(i * n + j, (i + 1) * n + j);
                            uf.union(index, index + n);
                        }
                    } else {
                        illegalCount++;
                    }
                }
            }
            // 3.返回合并之后集合的个数
            return uf.getCount() - illegalCount;
        }
    }
    //leetcode submit region end(Prohibit modification and deletion)
}